import Vue from 'vue'
import store from '@/store'
import VueRouter from 'vue-router'
import Layout from '@/views/layout'
import Search from '@/views/search'
import SearchList from '@/views/search/list'
import ProDetail from '@/views/prodetail'
import Login from '@/views/login'
import Pay from '@/views/pay'
import MyOrder from '@/views/myorder'

import Home from '@/views/layout/home'
import Category from '@/views/layout/category'
import Cart from '@/views/layout/cart'
import User from '@/views/layout/user'
import Demo from '@/views/demo/index'
import Detail from '@/views/goods/detail/index.vue'

Vue.use(VueRouter)

const routes = [{
  path: '/demo',
  component: Demo
}, {
  path: '/login',
  component: Login
}, {
  path: '/',
  component: Layout,
  redirect: '/home',
  children: [{
    path: 'home',
    component: Home
  }, {
    path: 'category',
    component: Category
  }, {
    path: 'cart',
    component: Cart,
    meta: { requiresAuth: true }
  }, {
    path: 'user',
    component: User
  }]
}, {
  path: '/search',
  component: Search
}, {
  path: '/search/list',
  component: SearchList
}, {
  path: '/prodetail/:id',
  component: ProDetail
}, {
  path: '/pay',
  component: Pay,
  meta: { requiresAuth: true }
}, {
  path: '/myorder',
  component: MyOrder,
  meta: { requiresAuth: true }
}, {
  path: '/goods/detail',
  component: Detail
}]

const router = new VueRouter({
  routes,
  scrollBehavior () {
    return { x: 0, y: 0 }
  }
})

router.beforeEach(async (to, from, next) => {
  const hasToken = store.getters['user/getToken']
  if (hasToken) {
    if (to.path === '/login') {
      // 跳登录页直接回首页
      next({ path: '/' })
      return
    }
  }
  // 公开页面
  if (!to.matched.some(record => record.meta.requiresAuth)) {
    next()
    return
  }
  // 非公开
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (hasToken) {
      next()
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 登录后回来源页
      })
    }
  }
})

export default router
